package com.hunzi.controller;

import com.hunzi.domain.Cart;
import com.hunzi.domain.CartItem;
import com.hunzi.domain.Item;
import com.hunzi.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private ItemService itemService ;

    //1.添加购物车功能
    @RequestMapping("/add")
    public String add(int id , int count , HttpServletRequest request){
        //1.根据id查询要购买的商品信息
        Item item = itemService.selectByPrimaryKey ( id );
        //2.创建购物项
        CartItem cartItem = new CartItem (item , count);

        //3.将购物项加入购物车
        //3.1、从session中取出name为cart的购物车
        Cart cart = (Cart) request.getSession ().getAttribute ( "cart" );
        if (cart==null){//如果没有取出说明还没购物车
            //1.创建购物车对象
             cart = new Cart ();
             //2.添加购物项
            cart.addCartItem ( cartItem );
            request.getSession ().setAttribute ( "cart" , cart );

        }else {
            //如果没有，直接添加
            cart.addCartItem ( cartItem );
        }
        return "cart";
    }

    //2.删除某一样商品
    @RequestMapping("/delete/{id}")
    public String delete (@PathVariable int id , HttpSession session){
        //1.获得session对象
        Cart cart = (Cart) session.getAttribute ( "cart" );
        if (cart!=null){
            cart.delete ( id );
            return "cart";
        }else {
            return "cart";
        }

    }
    //3.清空购物车
    @RequestMapping("/clear")
    public String clear ( HttpSession session){
        //1.获得session对象
        Cart cart = (Cart) session.getAttribute ( "cart" );
       cart.clear ();
       return "cart";
    }

}
